package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Login struct {
	User string `form:"user" json:"user" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

var login Login

func jsonHandle(c *gin.Context) {
	// ShouldBind() 会路径请求的Content-Type自行选择绑定器
	if err := c.ShouldBind(&login); err == nil {
		fmt.Println("%#v\n", login)
		c.JSON(http.StatusOK, gin.H{
			"user": login.User,
			"Password": login.Password,
		})
	}else {
		c.JSON(http.StatusBadRequest, gin.H{ "err": err.Error() })
	}
}

func formatHandle(c *gin.Context) {
	if err := c.ShouldBind(&login); err == nil{
		c.JSON(http.StatusOK, gin.H{
			"user": login.User,
			"password": login.Password,
		})
	}else{
	c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
}

func querystringHandle(c *gin.Context) {
	if err := c.ShouldBind(&login); err == nil{
		c.JSON(http.StatusOK, gin.H{
			"user": login.User,
			"password": login.Password,
		})
	}else{
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}
}
func main() {
	r := gin.Default()
	r.POST("/loginJson", jsonHandle)
	r.POST("/loginForm", formatHandle)
	r.GET("/loginForm", querystringHandle)

	r.Run(":8888")
}